This is the code I am using (but it only works for hyphens not for spaces)
console.log(
"some - text".replace(/\s\-/g, '').toLowerCase()
)
Can anyone point out what is wrong in this RegEx ?
The regex you have removes the space and the dash, leaving the second space
You need other regex to remove all spaces
console.log(
"some - text".replace(/\s\-/g, '') // space and dash
)
console.log(
"some - text".replace(/\s-\s/g, '') // space before and after a dash
)
console.log(
"some - text".replace(/\s+\-\s+/g, '') // any whitespace before and after
)
console.log(
"so- me - te-xt".replace(/\s|-/g, '') // all spaces and all dashes, can be written as a acharacter class [\s-]
)
Use\W for non-word character:
console.log("some - text".replace(/\W/g, '').toLowerCase())
Your regex is matching "(1 occurrence of some space)(definitely followed by 1 occurrence of ad ash)". You want it to match any occurrence of those, so use a character class in your regex (see: MDN WebDocs: JavaScript Character Classes, with brackets, /[\s\-]/g, like so:
console.log(
"some - text".replace(/[\s-]/g, '').toLowerCase()
)
Want to replace another character? Just throw it into the class and you're good to go.